<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="nav-content">
        <view class="back-btn" @click="goBack">
          <uni-icons type="arrowleft" size="20" color="#333"></uni-icons>
        </view>
        <text class="nav-title">选择收货地址</text>
      </view>
    </view>

    <!-- 搜索框 -->
    <view class="search-section">
      <view class="search-box">
        <uni-icons type="search" size="18" color="#999"></uni-icons>
        <input 
          class="search-input" 
          placeholder="搜索地点" 
          v-model="searchKeyword"
          @confirm="searchLocation"
        />
      </view>
    </view>

    <!-- 地图区域 -->
    <map 
      id="map"
      class="map-container"
      :longitude="longitude"
      :latitude="latitude"
      :markers="markers"
      scale="16"
      show-location
      @markertap="onMarkerTap"
    ></map>

    <!-- 地点列表弹窗 -->
    <view class="location-popup" :class="{ show: showLocationList }">
      <view class="popup-header">
        <text class="popup-title">附近地点</text>
      </view>
      
      <scroll-view class="location-list" scroll-y>
        <view 
          class="location-item" 
          v-for="(item, index) in locationList" 
          :key="index"
          @click="selectLocation(item)"
        >
          <view class="location-icon">
            <uni-icons type="location-filled" size="18" color="#ff6b6b"></uni-icons>
          </view>
          <view class="location-info">
            <text class="location-name">{{ item.name }}</text>
            <text class="location-address">{{ item.address }}</text>
          </view>
        </view>
        
        <view class="no-data" v-if="locationList.length === 0">
          <text>暂无地点信息</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';
// 引入全局配置
import { tencent_map } from '@/static/public.js';

export default {
  components: {
    uniIcons
  },
  data() {
    return {
      latitude: 39.9085,
      longitude: 116.3975,
      markers: [],
      searchKeyword: '',
      showLocationList: true,
      locationList: [],
      // 腾讯地图开发者key
      tencentMapKey: tencent_map.key,
      lastSearchTime: 0, // 添加最后搜索时间
      searchDelay: 1000  // 添加搜索延迟（毫秒）
    };
  },
  mounted() {
    // 初始化地图标记点
    this.initMarkers();
    
    // 获取当前位置
    this.getCurrentLocation();
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    
    toggleLocationList() {
      this.showLocationList = !this.showLocationList;
    },
    
    initMarkers() {
      this.markers = this.locationList.map(item => {
        return {
          id: item.id || 0,
          latitude: item.latitude,
          longitude: item.longitude,
          width: 25,
          height: 30
        };
      });
    },
    
    getCurrentLocation() {
      // 先检查是否有定位权限
      uni.getSetting({
        success: (res) => {
          // 如果已经授权
          if (res.authSetting['scope.userLocation']) {
            this.doGetLocation();
          } else {
            // 如果没有授权，请求授权
            uni.authorize({
              scope: 'scope.userLocation',
              success: () => {
                this.doGetLocation();
              },
              fail: () => {
                // 用户拒绝授权，引导用户手动开启
                this.showLocationAuthModal();
              }
            });
          }
        },
        fail: () => {
          // 获取设置失败，默认尝试获取位置
          this.doGetLocation();
        }
      });
    },
    
    // 实际获取位置的方法
    doGetLocation() {
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          console.log('获取位置成功', res);
          this.latitude = res.latitude;
          this.longitude = res.longitude;
          
          // 获取详细的地址信息
          this.getDetailedAddressForCurrentLocation(res.latitude, res.longitude);
        },
        fail: (err) => {
          console.log('获取位置失败', err);
          // 即使获取位置失败，也要确保地图能显示默认位置
          this.latitude = 39.9085;
          this.longitude = 116.3975;
          
          // 添加默认位置到列表
          const defaultLocation = {
            id: 0,
            name: '北京市',
            address: '北京市',
            latitude: 39.9085,
            longitude: 116.3975
          };
          
          this.locationList = [defaultLocation];
          this.initMarkers();
        }
      });
    },
    
    // 获取当前位置的详细地址信息
    getDetailedAddressForCurrentLocation(latitude, longitude) {
      // 检查请求频率限制
      const currentTime = Date.now();
      if (currentTime - this.lastSearchTime < this.searchDelay) {
        // 使用默认位置信息
        const currentLocation = {
          id: 0,
          name: '当前位置',
          address: `纬度:${latitude.toFixed(4)}, 经度:${longitude.toFixed(4)}`,
          latitude: latitude,
          longitude: longitude
        };
        
        // 添加当前位置到列表开头
        this.locationList.unshift(currentLocation);
        
        // 更新标记点
        this.initMarkers();
        
        // 获取附近的地点
        this.getNearbyLocations(latitude, longitude);
        return;
      }
      
      this.lastSearchTime = currentTime;
      
// 使用腾讯地图逆地址解析API
      const url = `${tencent_map.api}/ws/geocoder/v1/?key=${this.tencentMapKey}&location=${latitude},${longitude}&get_poi=1`;      
      uni.request({
        url: url,
        success: (res) => {
          console.log('逆地址解析结果:', res);
          let currentLocation;
          
          if (res.statusCode === 200 && res.data.status === 0) {
            // 成功获取详细地址信息
            const addressComponent = res.data.result.address_component || {};
            const formattedAddress = res.data.result.address || (res.data.result.formatted_addresses && res.data.result.formatted_addresses.recommend) || '未知位置';
            
            currentLocation = {
              id: 0,
              name: formattedAddress, // 使用实际地址名称
              address: formattedAddress,
              province: addressComponent.province || '',
              city: addressComponent.city || '',
              region: addressComponent.district || '',
              latitude: latitude,
              longitude: longitude
            };
          } else {
            // 获取详细地址失败，使用默认信息
            currentLocation = {
              id: 0,
              name: `纬度:${latitude.toFixed(4)}, 经度:${longitude.toFixed(4)}`,
              address: `纬度:${latitude.toFixed(4)}, 经度:${longitude.toFixed(4)}`,
              latitude: latitude,
              longitude: longitude
            };
          }
          
          // 添加当前位置到列表开头
          this.locationList.unshift(currentLocation);
          
          // 更新标记点
          this.initMarkers();
          
          // 获取附近的地点
          this.getNearbyLocations(latitude, longitude);
        },
        fail: (err) => {
          console.log('逆地址解析请求失败', err);
          // 请求失败，使用基本位置信息，但显示更友好的名称
          const currentLocation = {
            id: 0,
            name: '当前位置',
            address: `纬度:${latitude.toFixed(4)}, 经度:${longitude.toFixed(4)}`,
            latitude: latitude,
            longitude: longitude
          };
          
          // 添加当前位置到列表开头
          this.locationList.unshift(currentLocation);
          
          // 更新标记点
          this.initMarkers();
          
          // 获取附近的地点
          this.getNearbyLocations(latitude, longitude);
        }
      });
    },
    
    // 获取附近的地点
    getNearbyLocations(latitude, longitude) {
      // 检查请求频率限制
      const currentTime = Date.now();
      if (currentTime - this.lastSearchTime < this.searchDelay) {
        return; // 如果请求过于频繁，则跳过
      }
      
      this.lastSearchTime = currentTime;
      
// 使用腾讯地图API获取附近的POI
      const url = `${tencent_map.api}/ws/place/v1/nearby?key=${this.tencentMapKey}&keyword=*&boundary=nearby(${latitude},${longitude},1000)&page_size=20&page_index=1`;      
      uni.request({
        url: url,
        success: (res) => {
          if (res.statusCode === 200 && res.data.status === 0) {
            // 处理返回的数据
            const nearbyLocations = res.data.data.map((item, index) => {
              return {
                id: index + 1,
                name: item.title,
                address: item.address,
                latitude: item.location.lat,
                longitude: item.location.lng
              };
            });
            
            // 将附近地点添加到列表中（保留当前位置）
            const currentLocation = this.locationList.find(item => item.id === 0);
            if (currentLocation) {
              this.locationList = [currentLocation, ...nearbyLocations];
            } else {
              this.locationList = nearbyLocations;
            }
            
            // 更新标记点
            this.initMarkers();
          } else {
            console.log('获取附近地点失败', res);
          }
        },
        fail: (err) => {
          console.log('请求附近地点失败', err);
        }
      });
    },
    
    // 搜索地点
    searchLocation() {
      if (!this.searchKeyword) {
        uni.showToast({
          title: '请输入搜索关键词',
          icon: 'none'
        });
        return;
      }
      
      // 检查请求频率限制
      const currentTime = Date.now();
      if (currentTime - this.lastSearchTime < this.searchDelay) {
        uni.showToast({
          title: '请求过于频繁，请稍后再试',
          icon: 'none'
        });
        return;
      }
      
      this.lastSearchTime = currentTime;
      
      uni.showLoading({
        title: '搜索中...'
      });
      
// 使用腾讯地图API搜索地点
      const currentCity = this.locationList.length > 0 && this.locationList[0].city ? this.locationList[0].city : '北京';
      const url = `${tencent_map.api}/ws/place/v1/search?key=${this.tencentMapKey}&keyword=${this.searchKeyword}&boundary=region(${currentCity},0)&page_size=20&page_index=1`;      
      uni.request({
        url: url,
        success: (res) => {
          uni.hideLoading();
          
          if (res.statusCode === 200 && res.data.status === 0) {
            // 处理返回的数据
            this.locationList = res.data.data.map((item, index) => {
              return {
                id: index + 1,
                name: item.title,
                address: item.address,
                latitude: item.location.lat,
                longitude: item.location.lng
              };
            });
            
            // 更新标记点
            this.initMarkers();
            
            if (this.locationList.length > 0) {
              // 将地图中心移到第一个搜索结果
              this.latitude = this.locationList[0].latitude;
              this.longitude = this.locationList[0].longitude;
            }
            
            uni.showToast({
              title: `找到${this.locationList.length}个结果`,
              icon: 'none'
            });
          } else {
            console.log('搜索地点失败', res);
            // 添加更详细的错误提示
            let errorMsg = '搜索失败，请重试';
            if (res.data && res.data.message) {
              errorMsg = res.data.message;
            }
            uni.showToast({
              title: errorMsg,
              icon: 'none'
            });
            this.locationList = [];
            this.initMarkers();
          }
        },
        fail: (err) => {
          uni.hideLoading();
          console.log('请求搜索地点失败', err);
          uni.showToast({
            title: '网络错误，请重试',
            icon: 'none'
          });
          this.locationList = [];
          this.initMarkers();
        }
      });
    },
    
    // 显示权限引导弹窗
    showLocationAuthModal() {
      uni.showModal({
        title: '获取位置信息失败',
        content: '请授权位置权限以便获取您的当前位置，您可以在设置中手动开启',
        showCancel: true,
        confirmText: '去设置',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            // 打开设置页面
            uni.openSetting({
              success: (setting) => {
                if (setting.authSetting['scope.userLocation']) {
                  // 用户开启了权限，重新获取位置
                  this.doGetLocation();
                } else {
                  uni.showToast({
                    title: '未开启位置权限',
                    icon: 'none'
                  });
                }
              }
            });
          }
        }
      });
    },
    
    onMarkerTap(e) {
      const markerId = e.detail.markerId;
      const location = this.locationList.find(item => item.id === markerId);
      if (location) {
        this.selectLocation(location);
      }
    },
    
    // 选择位置
    selectLocation(location) {
      // 无论选择哪个位置，都直接返回
      this.returnLocationData(location);
    },
    
    // 返回位置数据到上一页
    returnLocationData(location) {
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      
      if (prevPage) {
        prevPage.$vm.updateLocation && prevPage.$vm.updateLocation(location);
      }
      
      uni.navigateBack();
    }
  }
};
</script>

<style scoped>
.container {
  width: 100%;
  height: 100vh;
  position: relative;
}

.navbar {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 44px;
  background-color: #fff;
  z-index: 100;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.nav-content {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 15px;
}

.back-btn {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.search-section {
  position: absolute;
  top: 60px;
  left: 15px;
  right: 15px;
  z-index: 100;
}

.search-box {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 20px;
  padding: 8px 15px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.search-input {
  flex: 1;
  margin-left: 8px;
  font-size: 14px;
}

.map-container {
  width: 100%;
  height: 100%;
}

.location-popup {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50%;
  background-color: #fff;
  border-top-left-radius: 15px;
  border-top-right-radius: 15px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  transform: translateY(100%);
  transition: transform 0.3s ease;
  z-index: 100;
}

.location-popup.show {
  transform: translateY(0);
}

/* 默认展开弹窗 */
.location-popup {
  transform: translateY(0);
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.popup-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.location-list {
  height: calc(100% - 50px);
}

.location-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f5f5f5;
}

.location-item:last-child {
  border-bottom: none;
}

.location-icon {
  margin-right: 10px;
}

.location-info {
  flex: 1;
}

.location-name {
  display: block;
  font-size: 15px;
  color: #333;
  margin-bottom: 5px;
}

.location-address {
  font-size: 13px;
  color: #999;
}

.no-data {
  text-align: center;
  padding: 30px 0;
  color: #999;
}

.toggle-btn {
  position: absolute;
  bottom: 50%;
  left: 50%;
  transform: translate(-50%, 50%);
  width: 40px;
  height: 20px;
  background-color: #ff6b6b;
  border-top-left-radius: 20px;
  border-top-right-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 101;
}
</style>